#pragma once
#include <iostream>
#include <string>
#include <sstream>
#include <filesystem>
#include <fstream>
#include <memory>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include "Mutex.hpp"

namespace MyLog
{
    using namespace MyMutex;

    const std::string default_path = "./log";     // 默认路径
    const std::string default_file = "mylog.log"; // 默认文件名

    // 刷新策略：策略模式
    class RefreshStrategy // 基类
    {
    public:
        virtual void Refresh(const std::string &message) = 0;
        virtual ~RefreshStrategy() = default;
    };

    class LogToConsole : public RefreshStrategy // 往控制台（显示器）刷新
    {
    public:
        LogToConsole() {}
        virtual void Refresh(const std::string &message) override
        {
            LockGuard lg(&_mutex); // 打印要加锁
            std::cout << message << "\r\n";
        }
        ~LogToConsole() {}

    private:
        Mutex _mutex;
    };

    class LogToFile : public RefreshStrategy // 往指定文件刷新
    {
    public:
        LogToFile(const std::string &path = default_path, const std::string &file = default_file)
            : _path(path),
              _file(file)
        {
            LockGuard lg(&_mutex);              // 加锁
            if (std::filesystem::exists(_path)) // 判断路径是否存在
                return;
            try
            {
                std::filesystem::create_directories(_path); // 创建路径
            }
            catch (const std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << '\n';
            }
        }

        virtual void Refresh(const std::string &message) override
        {
            LockGuard lg(&_mutex);                                                    // 加锁
            std::string file_name = _path + (_path.back() == '/' ? "" : "/") + _file; // 把路径和文件名拼起来
            std::ofstream out_file(file_name, std::ios::app);                         // 追加写入 的方式打开文件
            if (!out_file.is_open())                                                  // 打开失败直接返回
                return;
            out_file << message << "\r\n"; // 以流形式把message和换行符写到out_file里
            out_file.close();
        }

        ~LogToFile() {}

    private:
        std::string _path;
        std::string _file;
        Mutex _mutex;
    };

    enum class LogLevel
    {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };
    std::string LevelToStr(LogLevel lev)
    {
        switch (lev)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARNING:
            return "WARNING";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "UNKNOWN";
        }
    }

    // std::string GetTime()
    // {
    //     time_t curr_time = time(nullptr);
    //     struct tm stm;
    //     localtime_r(&curr_time, &stm);
    //     std::stringstream ss;
    //     ss << stm.tm_year + 1900 << "-"
    //        << stm.tm_mon + 1 << "-"
    //        << stm.tm_mday << " "
    //        << stm.tm_hour << ":"
    //        << stm.tm_min << ":"
    //        << stm.tm_sec;
    //     return ss.str();
    // }

    std::string GetTime()
    {
        time_t curr_time = time(nullptr);
        struct tm stm;
        localtime_r(&curr_time, &stm);
        char timebuffer[124];
        snprintf(timebuffer, 124, "%4d-%02d-%02d %02d:%02d:%02d",
                 stm.tm_year + 1900,
                 stm.tm_mon + 1,
                 stm.tm_mday,
                 stm.tm_hour,
                 stm.tm_min,
                 stm.tm_sec);
        return timebuffer;
    }

    class MyLog
    {
    public:
        MyLog()
        {
            RefreshLogToConsole(); // 默认往显示器刷新
        }

        void RefreshLogToConsole() // 选择刷新到显示器
        {
            _refresh_strategy = std::make_unique<LogToConsole>();
        }

        void RefreshLogToFile() // 选择刷新到文件
        {
            _refresh_strategy = std::make_unique<LogToFile>();
        }

        class LogMessage // 内部类
        {
        public:
            LogMessage(LogLevel log_level, std::string filename, int line, MyLog &log)
                : _log_level(log_level),
                  _curr_time(GetTime()),
                  _pid(getpid()),
                  _filename(filename),
                  _line(line),
                  _log(log)
            {
                std::stringstream ss; // 定义一个stringstream流
                // 类型自动转化为string对象然后，把所有内容格式化输入到这个流里，
                ss << "[" << _curr_time << "]"
                   << "[" << LevelToStr(_log_level) << "]" // 转化
                   << "[" << _pid << "]"
                   << "[" << _filename << "]"
                   << "[" << _line << "]"
                   << " - ";
                _log_info = ss.str();
            }

            template <typename T> // 类型自动推导
            LogMessage &operator<<(const T &info)
            {
                std::stringstream ss; // 还是用stringstream流
                ss << info;
                _log_info += ss.str(); // 消息前后部分拼起来
                return *this;
            }

            ~LogMessage()
            {
                if (_log._refresh_strategy)
                {
                    _log._refresh_strategy->Refresh(_log_info); // 刷新日志信息
                }
            }

        private:
            LogLevel _log_level;    // 日志等级
            std::string _curr_time; // 时间
            pid_t _pid;             // 进程ID
            std::string _filename;  // 文件名
            int _line;              // 行号
            std::string _log_info;  // 合并之后的消息
            MyLog &_log;            // 外部类的引用
        };

        LogMessage operator()(LogLevel level, std::string filename, int line)
        {
            return LogMessage(level, filename, line, *this);
        }

        ~MyLog() {}

    private:
        std::unique_ptr<RefreshStrategy> _refresh_strategy;
    };

    MyLog mylog; // 定义全局日志对象
#define LOG(level) mylog(level, __FILE__, __LINE__)
#define Refresh_Log_To_Console() mylog.RefreshLogToConsole() // 显示器
#define Refresh_Log_To_File() mylog.RefreshLogToFile()       // 文件

}
